let q = {
    pagenum: 1,
    pagesize: 2,
    cate_id: '',
    state: '',
}
//  需求1，封装成函数，将来反复调用
let layer = layui.layer
initArticleList()
function initArticleList() {
    // 发送axios
    axios({
        method: 'GET',
        url: '/my/article/list',
        params: q,
    }).then(function (res) {
        if (res.data.status !== 0) {
            return layer.msg(res.data.message)
        }
        let arr = []
        res.data.data.forEach((ele) => {
            arr.push(`
            <tr>
            <td>${ele.title}</td>
            <td>${ele.cate_name}</td>
            <td>${ele.pub_date}</td>
            <td>${ele.state}</td>
            <td>
              <button class="layui-btn layui-btn-xs">编辑</button>
              <button data-id="${ele.Id}" class="del-btn layui-btn layui-btn-danger layui-btn-xs">删除</button>
            </td>
          </tr>
            `)
        })
        $('tbody').empty().html(arr.join(''))
        renderPage(res.data.total)
    })
}
// 需求2 渲染选中的文章类别列表
let form = layui.form
initArtCateList()
function initArtCateList() {
    // 发送axios
    axios({
        url:'/my/article/cates',
    }).then(function (res) {
        if(res.data.status !== 0){
            return layer.msg(res.data.message)
        }
        let arr = ['<option value="">请选择类别</option>']
        res.data.data.forEach((ele)=>{
            arr.push(`
            <option value="${ele.Id}">${ele.name}</option>
            `)
        })
        $('[name=cate_id]').empty().html(arr.join(''))
        form.render()
    })
}
// 需求3 筛选
$('#searchForm').on('submit',function (e) {
    e.preventDefault()
    q.cate_id = $('[name="cate_id"]').val()
    q.state = $('[name=state]').val()
    initArticleList()
})
// 分页

function renderPage(total) {
    let laypage = layui.laypage

    laypage.render({
    elem:'pageBox',
    count:total,
     limit:q.pagesize,
     curr:q.pagenum,
    layout:['count','limit','prev','page','next','refresh','skip'],
    limits:[2,3,5,10],
    jump:function (obj,first) {
        if(!first){
            q.pagenum = obj.curr 
            q.pagesize= obj.limit
            initArticleList()
        }
    }
})
}
// 删除 用事件委托
$('tbody').on('click','.del-btn',function () {
    let id = $(this).attr('data-id')
    //alert(id)
    // 发送axios
    layer.confirm('确认删除吗？',function (index) {
        axios({
        method:'GET',
        url:'/my/article/delete/'+id,
    }).then(function (res) {
        if(res.data.status !== 0){
            return layer.msg(res.data.message)
        }
        layer.msg('恭喜您，删除成功')
        // 优化，短路运算
        $('.del-btn').length ==1 && q.pagenum >=2 && q.pagenum--;
        initArticleList()
    })
    layer.close(index)
    })
    
})

